const { authCheck } = require('../middleware/auth_middleware')
const { ChatRecord } = require('../controller/Chat_controller')
//添加中间件校验 
const { isFriend } = require('../services/FriendService')
const { token: Authorization } = require('../config/config_deafault')
const axios = require('axios')
//控制器写入数据库
let io = null

//创建对象集合
const ChatUser = {}
function initSocketio(server) {
    const socketio = require('socket.io');
    io = socketio(server, {
        maxHttpBufferSize: 10 * 1024 * 1024,
        cors: {
            origin: "*",
            methods: ["GET", "POST"]
        },
    })

    //监听服务器端连接事件
    io.on('connect', async (socket) => {
        const token = socket.handshake.headers.authorization

        //校验token
        if (!token) {
            socket.disconnect(true)
            return
        }
        //校验token是否过期
        try {
            const res = await authCheck(token)
            ChatUser[res] = socket.id
            console.log(ChatUser);
        }
        catch (error) {
            if (error) {
                socket.emit('token', "token已过期")
            }
            return socket.disconnect(true)
        }
        socket.emit('message', "服务器已经连接")
        // 监听私聊事件
        socket.on('privateChat', async ({ receiveid, message }, callback) => {
            //校验用户是否为好友
            let sendid = null
            try {
                sendid = await authCheck(token)
                const Friendrealtion = await isFriend(sendid, receiveid)
                if (Friendrealtion.length == 0) {
                    io.to(ChatUser[sendid]).emit('token', "你们还不是好友关系")
                }
            }
            catch (error) {
                console.log(error);

            }
            //存入数据库
            const res = await ChatRecord({ senderId: sendid, receiverId: receiveid, type: 1, message })
            //如果房间存在则发送消息
            const roomid = ChatUser[receiveid]
            if (roomid) {
                //to 点对点进行交互
                io.to(roomid).emit('privateChat', res)
            }
            //检测类型 
            callback(res)
        })
        //监听私聊图片事件 
        socket.on('privateBuffer', async ({ receiveid, file, filename }, callback) => {
            const file_MAXSIZE = 5 * 1024 * 1024
            const fileSizeInBytes = file.byteLength || file.length;
            // 转换为MB进行比较 (1MB = 1024 * 1024 bytes)
            const fileSizeInMB = fileSizeInBytes / (1024 * 1024);
            let sendid = null
            if (fileSizeInMB > file_MAXSIZE) {
                return callback({
                    success: 'fail',
                    message: '文件超过最大限制大小5MB'
                })
            }
            try {
                sendid = await authCheck(token)
                const Friendrealtion = await isFriend(sendid, receiveid)
                if (Friendrealtion.length == 0) {
                    io.to(ChatUser[sendid]).emit('token', "你们还不是好友关系")
                }
            }
            catch (error) {
                console.log(error);

            }
            try {
                //建立表单发送给图床
                const blob = new Blob([new Uint8Array(file)]);

                const formdata = new FormData()
                formdata.append('file', blob, filename)
                const res = await axios.post(`http://skypro.afterglow26.cn:28080/api/v1/upload`, formdata, {
                    headers: {
                        Authorization,
                        "Content-Type": "multipart/form-data"
                    }
                })
                //获取图床返回消息
                let image = null
                let imagekey = null
                if (res.data.status == true) {
                    imagekey = res.data.data.key
                    image = res.data.data.links.url
                }
                const imageObj = JSON.stringify({ image, imagekey })
                let ResMessage = await ChatRecord({ senderId: sendid, receiverId: receiveid, type: 2, message: imageObj })

                ResMessage.message = { image: JSON.parse(ResMessage.message).image }
                //得到数据库返回数据  消息处理
                const roomid = ChatUser[receiveid]
                if (roomid) {
                    //to 点对点进行交互
                    io.to(roomid).emit('privateBuffer', ResMessage)
                }
                callback(ResMessage)
            }
            catch (error) {
                console.log(error);

            }
        })
        //监听发送音乐事件
        socket.on('privateMuisc', async ({ receiveid, musicinfo }, callback) => {
            let sendid = null
            try {
                sendid = await authCheck(token)
                console.log(sendid);
                console.log(receiveid);

                const Friendrealtion = await isFriend(sendid, receiveid)
                console.log(Friendrealtion);

                if (Friendrealtion.length == 0) {
                    io.to(ChatUser[sendid]).emit('token', "你们还不是好友关系")
                }
            }
            catch (error) {
                console.log(error);

            }
            //存入数据库
            const ResMessage = await ChatRecord({ senderId: sendid, receiverId: receiveid, type: 3, message: musicinfo })
            ResMessage.message = JSON.parse(ResMessage.message)
            //如果房间存在则发送消息
            const roomid = ChatUser[receiveid]
            const sendroomid = ChatUser[sendid]
            if (roomid) {
                //to 点对点进行交互
                io.to(roomid).emit('privateMusic', ResMessage)
            }
            //非同一个组件 需要对在线组件实时返回消息接收
            if (sendroomid) {
                io.to(sendroomid).emit('privateSendMusic', ResMessage)
            }
            callback({ status: 'success' })
        })
        //监听服务器连接断开事件
        socket.on('disconnect', (data) => {
            console.log('客户端已断开连接', data);
        })
    })

}

function getSocketio() {
    if (!io) {
        throw new Error("io实例不存在");
    }
    return io
}

module.exports = { initSocketio, getSocketio }